package lion.dev.encrypt.cert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

/**
 * @author lion
 * @email hl_0074@sina.com
 * @date 2016年3月4日
 */
public class DName {

	private String CN;// CommonName 使用者
	private String O;// Organization 组织
	private String L; // locality 城市
	private String ST;// state/provice 省份
	private String C;// country 国家
	private String E;// email
	private String OU;// 其他字段

	private Map<String, String> extMap = new HashMap<>();

	public String getCN() {

		return CN;
	}

	public void setCN(String cN) {

		CN = cN;
	}

	public String getO() {

		return O;
	}

	public void setO(String o) {

		O = o;
	}

	public String getL() {

		return L;
	}

	public void setL(String l) {

		L = l;
	}

	public String getST() {

		return ST;
	}

	public void setST(String sT) {

		ST = sT;
	}

	public String getC() {

		return C;
	}

	public void setC(String c) {

		C = c;
	}

	public String getE() {

		return E;
	}

	public void setE(String e) {

		E = e;
	}

	public String getOU() {

		return OU;
	}

	public void setOU(String oU) {

		OU = oU;
	}

	public void set(String key, String value) {

		this.extMap.put(key, value);
	}

	public String get(String key) {

		return this.extMap.get(key);
	}

	public static DName parse(String field) {

		String[] fields = field.split(",");
		DName subject = new DName();

		for (String f : fields) {
			String[] ks = f.trim().split("=");
			if (ks.length != 2) {
				continue;
			}
			switch (ks[0]) {
			case "CN":
				subject.setCN(ks[1]);
				break;
			case "O":
				subject.setO(ks[1]);
				break;
			case "L":
				subject.setL(ks[1]);
				break;
			case "ST":
				subject.setST(ks[1]);
				break;
			case "C":
				subject.setC(ks[1]);
				break;
			case "E":
				subject.setE(ks[1]);
				break;
			case "OU":
				subject.setOU(ks[1]);
				break;
			default:
				subject.set(ks[0], ks[1]);
				break;
			}
		}
		return subject;
	}

	@Override
	public String toString() {

		List<String> strs = new ArrayList<>();
		add(strs, "CN", this.CN);
		add(strs, "O", this.O);
		add(strs, "L", this.L);
		add(strs, "ST", this.ST);
		add(strs, "C", this.C);
		add(strs, "E", this.E);
		add(strs, "OU", this.OU);

		for (String key : this.extMap.keySet()) {
			add(strs, key, this.get(key));
		}

		return StringUtils.join(strs, ", ");
	}

	private void add(List<String> strs, String key, String value) {

		if (StringUtils.isNotBlank(value)) {
			strs.add(key + "=" + value);
		}
	}
}
